package callnumber.gtdev5.com.photoVault.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.gtdev5.geetolsdk.mylibrary.util.PermissionUtils;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;
import com.zhihu.matisse.Matisse;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.RandomAccessFile;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.adapter.ImageChoseAdapter1;
import callnumber.gtdev5.com.photoVault.base.BaseActivity;
import callnumber.gtdev5.com.photoVault.bean.FileNameBean;
import callnumber.gtdev5.com.photoVault.utils.DialogUtils;
import callnumber.gtdev5.com.photoVault.utils.FileSizeUtil;
import callnumber.gtdev5.com.photoVault.utils.ImageUtils;
import callnumber.gtdev5.com.photoVault.utils.MatisseUtil;
import callnumber.gtdev5.com.photoVault.utils.getPathUtil;

public class PhotoActivity extends BaseActivity {
    @BindView(R.id.rc_imag)
    RecyclerView rcImag;
    private ImageChoseAdapter1 adapter;
    @BindView(R.id.button)
    Button button;
    List<String> strings;
    List<Bitmap> str;
    private Dialog mWeiboDialog;
    private List<FileNameBean> dataName;
    private static final int COMPLETED = 0;
    int ids;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == COMPLETED) {
                GridLayoutManager manager = new GridLayoutManager(getApplicationContext(), 3);
                rcImag.setLayoutManager(manager);
                adapter.AddDatas(str);
                rcImag.setAdapter(adapter);
                DialogUtils.closeDialog(mWeiboDialog);
            }
        }
    };
    int curent_position;
    List<FileNameBean> newsList;

    @Override
    protected int getLayouId() {
        return R.layout.activity_photo;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        getData();
        ids = getIntent().getIntExtra("ids", 0);
        mWeiboDialog = DialogUtils.createLoadingDialog(PhotoActivity.this, "加载中...");
//        checkPermission();
        new WorkThread().start();

    }

    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        }
    }


    public void getData() {
        dataName = new ArrayList<>();
        dataName = DataSupport.findAll(FileNameBean.class);
        newsList = new ArrayList<>();
        newsList = DataSupport.where("ids = ?", ids + "").find(FileNameBean.class);
        adapter = new ImageChoseAdapter1(this, 20, null, newsList, new ImageChoseAdapter1.OnItemClickListener() {
            @Override
            public void OnItemClick(int position) {
                curent_position = position;
                Intent intent = new Intent(PhotoActivity.this, ImagePagerActivity.class);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                intent.putExtra("ids", ids);
                startActivityForResult(intent, 115);

            }

            @Override
            public void OnAddItemClick(int count) {   //count 剩余可添加的数量
                String filePath = "/sdcard/encryption";
                File file = new File(filePath);
                if (file.exists()) {
                    //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                    double s = FileSizeUtil.getFileOrFilesSize(filePath, 3);
                    double two = 100;
                    String re = FileSizeUtil.getDouble(s, two);
                    if (vip.isIsout() && re.equals("1")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
                        builder.setTitle("警告：");
                        builder.setMessage("内存已满，请前往首页开通会员！");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        builder.show();


                    } else {
                        MatisseUtil.GetPhoto(PhotoActivity.this, count, 1113, 114);
                    }
                } else if (!file.exists()) {
                    //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                    file.mkdirs();
                }
            }
        });

//        if (datas != null && !datas.isEmpty()) {
//            strings = new ArrayList<>();
//            for (PhotoBean photoBean : datas) {
////                strings.add( Des3Util.decrypt(key, photoBean.getUri()));
//                strings.add(ImageBase64.stringtoBitmap(Des3Util.decrypt(key, photoBean.getUri())));
//            }
//            adapter.AddDatas(strings);
//        }
        if (newsList != null && !newsList.isEmpty()) {
            str = new ArrayList<>();
            strings = new ArrayList<>();
            for (FileNameBean fileNameBean : newsList) {
                if (ImageUtils.fileIsExists(fileNameBean.getName())) {
                    String text = fileNameBean.getName();
//                    ImageUtils.renameFile(fileNameBean.getName(), text);
//                    File file = new File(text);0

//                    String s = ImageUtils.getFileContent(file);
//                    String con = Des3Util.decrypt(key, s);
                    Bitmap bitmap = BitmapFactory.decodeFile(text);//从路径加载出图片bitmap
                    strings.add(text);
                    str.add(bitmap);
//                    ImageUtils.renameFile(text, fileNameBean.getName());
                }

            }

        }

    }


    //工作线程
    private class WorkThread extends Thread {
        @Override
        public void run() {
            //......处理比较耗时的操作
            //处理完成后给handler发送消息
            getData();
            Message msg = new Message();
            msg.what = COMPLETED;
            handler.sendMessage(msg);
        }
    }

    @Override
    protected void initDatas() {

    }

    @Override
    protected void initAction() {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case 114:
                    mWeiboDialog = DialogUtils.createLoadingDialog(PhotoActivity.this, "加载中...");
                    List<Uri> list2 = Matisse.obtainResult(data);
                    if (null != list2 && list2.size() > 0) {
//                        List<String> strings = new ArrayList<>();
                        int i = 0;
                        for (Uri uri : list2) {
                            String fileName = "/" +  ImageUtils.getStringRandom(28);
                            String filePath = "/sdcard/encryption/photo";
                            File file = new File(filePath);
//判断文件夹是否存在，如果不存在就创建，否则不创建
                            if (!file.exists()) {
                                //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
                                file.mkdirs();
                            }

                            String oldPath = getPathUtil.getRealPathFromURI(getApplicationContext(), uri);
                            String newPath = filePath + fileName;
                            ImageUtils.renameFile(oldPath, newPath);
                            FileNameBean fileNameBean = new FileNameBean();
                            fileNameBean.setIds(ids);
                            fileNameBean.setName(filePath + fileName);
                            fileNameBean.save();
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + oldPath)));
                            ToastUtils.showShortToast("完成");
//                            try {
//   /data/user/0/com.junruy.fakecall/files/Test/
                            /// /storage/emulated/0/Xiaomi/WALI_LIVE/levelPic/81634374ed373849.png
////                                String s = Des3Util.encrypt(key, ImageUtils.Bitmap2StrByBase64(ImageUtils.getBitmapFormUri(PhotoActivity.this, uri)));
////                                strings.add( ImageUtils.Bitmap2StrByBase64(ImageUtils.getBitmapFormUri(PhotoActivity.this, uri )));
//
////                                new PhotoBean(s).save();
////                                writeTxtToFile(s, filePath, fileName);
//
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }

//    ImageBase64.DeletePicFromMobile(
//     getApplicationContext(),
//            getPathUtil.getRealPathFromURI(
//     getApplicationContext(), uri));//删除图片
                        }
//                        adapter.AddDatas(strings);
                        new WorkThread().start();
                    }
                    break;

//            case 115:
//                List<String> list = data.getStringArrayListExtra("mes");
//                if (null != list && list.size() > 0) {
//                    for (String s : list) {
//                        int nim = Integer.parseInt(s);
//                        String text = newsList.get(nim).getName();
//                        Bitmap bitmap = BitmapFactory.decodeFile(text);
//                        adapter.repeleceData(bitmap, nim);
//                    }
//
//                }
//                break;
            }
        }
    }

    public static class RandomUtil {
        /**
         * 生成随机文件名：当前年月日时分秒+五位随机数
         *
         * @return
         */
        public static String getRandomFileName() {

            SimpleDateFormat simpleDateFormat;

            simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

            Date date = new Date(System.currentTimeMillis());

            String str = simpleDateFormat.format(date);

            Random random = new Random();

            int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数

            return rannum + str;// 当前时间
        }
    }

    // 将字符串写入到文本文件中

    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1113)
            PermissionUtils.onRequestMorePermissionsResult(this, MatisseUtil.PICTURE_PERMISSION, new PermissionUtils.PermissionCheckCallBack() {
                @Override
                public void onHasPermission() {
                    ToastUtils.showShortToast("授权成功");
                }

                @Override
                public void onUserHasAlreadyTurnedDown(String... strings) {
                    ToastUtils.showShortToast("授予此权限才能添加照片哦,点击确定继续授权。");
                    PermissionUtils.requestMorePermissions(PhotoActivity.this, MatisseUtil.PICTURE_PERMISSION, 1113);
                   /* DialogManager.getInstanse(CreatProductActivity.this).Show2BtTipDialog(mContext,"授予此权限才能添加照片哦,点击确定继续授权。", new DialogManager.OnDialogBaseLickListener() {
                        @Override
                        public void OnDialogDis() {

                        }

                        @Override
                        public void OnDialogOk() {
                            PermissionUtils.requestMorePermissions(CreatProductActivity.this, Constant.PICTURE_PERMISSION,111);
                        }
                    });*/
                }

                @Override
                public void onUserHasAlreadyTurnedDownAndDontAsk(String... strings) {
                    ToastUtils.showShortToast("您已经拒绝授权，无法继续添加照片，点击确定进入设置开启授权");
                    PermissionUtils.toAppSetting(PhotoActivity.this);
                    /*DialogManager.getInstanse(CreatProductActivity.this).Show2BtTipDialog(mContext,"您已经拒绝授权，无法继续添加照片，点击确定进入设置开启授权", new DialogManager.OnDialogBaseLickListener() {
                        @Override
                        public void OnDialogDis() {

                        }

                        @Override
                        public void OnDialogOk() {
                            PermissionUtils.toAppSetting(CreatProductActivity.this);
                        }
                    });*/
                }
            });
    }
}
